<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>

    </style>
</head>

<body>
    <canvas id="webgl" width="700" height="700" style="background: #000;"></canvas>
    <script>
        const canvas = document.getElementById('webgl');
        const gl = canvas.getContext('webgl');

        const vertexShaderSource = `
            attribute vec2 aPosition;
            attribute vec4 aColor;
            varying vec4 vColor;
            void main(){
                gl_Position  = vec4(aPosition, 0.0,1.0);
                vColor = aColor;
            }
            `;
        const fragShaderSource = `
            // 使用高精度，float类型
            precision highp float;
            varying vec4 vColor;
            void main() {
                gl_FragColor = vColor;
            }
        `;

        // 创建顶点着色器对象
        const vertexShader = gl.createShader(gl.VERTEX_SHADER);
        // 创建片元着色器对象
        const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        // 引入顶点、片元着色器源码
        gl.shaderSource(vertexShader, vertexShaderSource);
        gl.shaderSource(fragmentShader, fragShaderSource);
        // 编译顶点、片元着色器
        gl.compileShader(vertexShader);
        gl.compileShader(fragmentShader);
        // 创建程序对象 program
        const program = gl.createProgram();
        // 附着顶点着色器和片元着色器到program
        gl.attachShader(program, vertexShader);
        gl.attachShader(program, fragmentShader);
        // 链接program
        gl.linkProgram(program);
        // 使用program
        gl.useProgram(program);
        // 使用类型化数组
        const vertices = new Float32Array([
            -0.5, -0.5, // 第一个点的y轴和y轴坐标
            0.5, 0.5, // 第二个点的y轴和y轴坐标
        ]);
        // 创建颜色数组
        const colors = new Float32Array([
            1.0, 1.0, 1.0, 1.0, // 白色
            1.0, 0.0, 0.0, 0.0 // 红色
        ]);
        // 创建缓冲区
        const buffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

        const posLocation = gl.getAttribLocation(program, 'aPosition');
        // 动态赋值
        gl.vertexAttribPointer(posLocation, 2, gl.FLOAT, false, 2 * Float32Array.BYTES_PER_ELEMENT, 0);
        // 启用指定的顶点属性数组
        gl.enableVertexAttribArray(posLocation);
        const colorLocation = gl.getAttribLocation(program, 'aColor');
        // 创建缓冲区
        const colorBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW);
        gl.vertexAttribPointer(colorLocation, 4, gl.FLOAT, false, 4 * Float32Array.BYTES_PER_ELEMENT, 0);
        gl.enableVertexAttribArray(colorLocation);

        // 开始绘制，显示器显示结果
        gl.drawArrays(gl.LINES, 0, 2);

    </script>
</body>

</html>